/*
 ============================================================================
 Name        : restore.c
 Author      : chenf
 Version     : 1.0
 Copyright   : loongsec
 Description : add phase in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

#define UP_FILEPATH "/home/upload.db"
#define MV_CMD      "mv /home/upload.db /home/loongsec/database/database.db"

int strindex(char *str1, char *str2, size_t n){
    if(n<strlen(str2)){
        return -2;
    } else {
        int clen = strlen(str2);
        int i = 0;

        for(i=0;i<clen;i++){
            if(str1[i] != str2[i]){
                int t = strindex(str1+1, str2, n-1);
                if(t>=0)
                    return 1+t;
                else
                    return -1;
            } else {
                continue;
            }
        }
        return 0;
    }
}

int strindexl(char *str1, char *str2, size_t n){
    int lindex = -1;
    int i = 0;
    while(n>i){
        int b = strindex(str1+i, str2, n-i);
        if(b>=0){
            lindex = i + b;
        } else{
            break;
        }
        i++;
    }
    return lindex;
}


int strlindex(char *str1, char *str2, size_t n){
    int lindex = strindex(str1, str2, n);
    int offset = lindex + strlen(str2);

    while(n>offset){
        int b = strindex(str1+offset, str2, n-offset);
        if(b>=0){
            lindex = offset + b;
        } else{
            break;
        }
        offset = lindex + strlen(str2);
    }
    return lindex;
}


int main(void) {
    char *content_type = getenv("CONTENT_TYPE");

    int cl = atoi(getenv("CONTENT_LENGTH"));

    FILE* fp = fopen(UP_FILEPATH, "wb");
    char buf[5];
    int size = 0;
    char *word = (char*)malloc(sizeof(char) * cl);

    printf("Content-type:text/html;charset=utf-8\n\n");

    char lsp[] = {0x0d, 0x0a, 0x0d, 0x0a, '\0'};
    //char wsp[] = {0x0a, 0x0a, '\0'};
    char *sp = lsp;

    
    if(fp!=NULL){
        fread(word, 1, cl, (FILE*)stdin);
    
        rewind((FILE*)stdin);
        char flag[100] = {0};
        
        fgets(flag,100, (FILE*)stdin);
        int hof = strindex(word, sp, cl);
        int eof = strindexl(word, sp, cl);
    
        fwrite(word+hof+4, 1, cl-strlen(flag)-4 - (hof+4), fp);
        /*
        int i;
        for(i =hof+4;i<cl-strlen(flag)-4;i++){
            if(word[i]== 0x0d)
                printf("%d,c=[CR]\n",i);
            else if(word[i]== 0x0a)
                printf("c=[LF]\n");
            else
                printf("c=[%c]\n",word[i]);
        }
        */
        fclose(fp);
        free(word);
    } else {
        //printf("file open faild.\n");
        printf("文件错误\n");
    }
    //printf("CONTENT_TYPE: %s\n", content_type);
    //printf("CONTENT_LENGTH: %d\n", cl);
    if(system(MV_CMD)==0)
        printf("导入完成 \n");
    else
        printf("导入失败\n");

    return EXIT_SUCCESS;
}
